package com.example.allfilemanagerdemo

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.text.TextUtils
import android.widget.TextView
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.allfilemanagerdemo.utils.Constants
import com.example.allfilemanagerdemo.utils.Constants.Companion.REQUIRED_PERMISSIONS
import com.example.allfilemanagerdemo.utils.FileUtils
import com.example.allfilemanagerdemo.utils.FileUtils.getImageAbsolutePath
import com.example.allfilemanagerdemo.utils.MyImageGlideEngine
import com.luck.picture.lib.basic.PictureSelector
import com.luck.picture.lib.config.SelectMimeType
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener


class MainActivity : AppCompatActivity() {
    private val textView: TextView by lazy { findViewById(R.id.tv_choose) }
    private val tvAlbums: TextView by lazy { findViewById(R.id.tv_albums) }
    private val ivBg: AppCompatImageView by lazy { findViewById(R.id.iv_bg) }
    private val ivCamera: AppCompatImageView by lazy { findViewById(R.id.iv_camera) }
    private val tvPhoto: AppCompatTextView by lazy { findViewById(R.id.tv_photo) }
    private val ivPhoto: AppCompatImageView by lazy { findViewById(R.id.iv_photo) }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initPermission()
        initView()
    }

    private fun initPermission() {
        if (checkPermissions()) {
            takePhoto()
        } else {
            requestPermission()
        }
    }

    fun takePhoto() {
        textView?.setOnClickListener {//选择相册
            PictureSelector.create(this)
                .openGallery(SelectMimeType.ofImage())
                .setImageEngine(MyImageGlideEngine.createGlideEngine())
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: ArrayList<LocalMedia?>) {
                        LogUtils.d("===返回的图片地址为===", result[0]!!.path)
                        Glide.with(this@MainActivity).load(result[0]?.path).into(ivBg)
                    }

                    override fun onCancel() {}
                })
        }
        tvAlbums?.setOnClickListener {//拍照
            PictureSelector.create(this)
                .openCamera(SelectMimeType.ofImage())
                .forResult(object : OnResultCallbackListener<LocalMedia?> {
                    override fun onResult(result: ArrayList<LocalMedia?>) {
                        LogUtils.d("===返回的图片地址为===", result[0]!!.path)
                        Glide.with(this@MainActivity).load(result[0]?.path).into(ivCamera)
                    }

                    override fun onCancel() {}
                })
        }

        tvPhoto.setOnClickListener {
            openPhotoAlbum()
        }
    }

    private val photoLaunch =
        registerForActivityResult(ActivityResultContracts.GetContent()) { uri ->
            Glide.with(this@MainActivity).load(uri.toString()).into(ivPhoto)
        }


    private fun openPhotoAlbum() {
        val intent = Intent(Intent.ACTION_GET_CONTENT)
        intent.addCategory(Intent.CATEGORY_OPENABLE)
        intent.type = "image/*"
        //以startActivityForResult方式打开Activity
        /*        startActivityForResult(
                    Intent.createChooser(intent, "File Browser"), Constants.FILE_CHOOSER_RESULT_CODE)*/
        //以launch方式打开相册
        photoLaunch.launch("image/*")
    }

    private fun requestPermission() {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                ActivityCompat.requestPermissions(
                    this,
                    arrayOf(
                        Manifest.permission.READ_MEDIA_IMAGES,
                        Manifest.permission.READ_MEDIA_AUDIO,
                        Manifest.permission.READ_MEDIA_VIDEO,
                        Manifest.permission.CAMERA,
                    ),
                    Constants.REQUEST_CODE_PERMISSIONS
                )
            }

            else -> {
                ActivityCompat.requestPermissions(
                    this,
                    REQUIRED_PERMISSIONS,
                    Constants.REQUEST_CODE_PERMISSIONS
                )
            }
        }
    }

    private fun initView() {

    }

    private fun checkPermissions(): Boolean {
        when {
            Build.VERSION.SDK_INT >= 33 -> {
                val permissions = arrayOf(
                    Manifest.permission.READ_MEDIA_IMAGES,
                    Manifest.permission.READ_MEDIA_AUDIO,
                    Manifest.permission.READ_MEDIA_VIDEO,
                    Manifest.permission.CAMERA,
                )
                for (permission in permissions) {
                    return Environment.isExternalStorageManager()
                }
            }

            else -> {
                for (permission in REQUIRED_PERMISSIONS) {
                    if (ContextCompat.checkSelfPermission(
                            this,
                            permission
                        ) != PackageManager.PERMISSION_GRANTED
                    ) {
                        return false
                    }
                }
            }
        }
        return true
    }

    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<String>, grantResults:
        IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            Constants.REQUEST_CODE_PERMISSIONS -> {
                var allPermissionsGranted = true
                for (result in grantResults) {
                    if (result != PackageManager.PERMISSION_GRANTED) {
                        allPermissionsGranted = false
                        break
                    }
                }
                when {
                    allPermissionsGranted -> {
                        // 权限已授予，执行文件读写操作
                        takePhoto()
                    }

                    else -> {
                        // 权限被拒绝，处理权限请求失败的情况
                        ToastUtils.showShort("请您打开必要权限")
                        requestPermission()
                    }
                }
            }

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != RESULT_OK) {
            return
        }
        when (requestCode) {
            Constants.FILE_CHOOSER_RESULT_CODE -> {
                if (data?.data == null) {
                    return
                }
                val imgStr: String = getImageAbsolutePath(this, data.data).toString()
                if (!TextUtils.isEmpty(imgStr)) {
                    val imgUri: Uri? = FileUtils.getUriFromPath(imgStr, application)
                    if (imgUri != null) {
                        Glide.with(this@MainActivity).load(imgUri.toString()).into(ivPhoto)
                    }
                }
            }
        }
    }
}